/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is About:History
 *
 * The Initial Developer of the Original Code is Chris Jay.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Chris Jay <chris.f.jay@gmail.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

//get querystring values
var inputparams = {};
if (document.URL.split('?')[1]) {
    unescape(document.URL.replace(/\+/g, ' ')).split('?')[1].split('&').forEach(function(queryval) {
        if (queryval.split('=')[1]) {
            inputparams[queryval.split('=')[0]] = unescape(queryval.split('=')[1]); 
        }
    });
}
//validate inputparams
inputparams.q = inputparams.q ? inputparams.q : "";
inputparams.a = isNaN((new Date(inputparams.a)).getFullYear()) ? "" : (new Date(inputparams.a));
inputparams.b = isNaN((new Date(inputparams.b)).getFullYear()) ? "" : (new Date(inputparams.b));
inputparams.start = 0;

//execute search
var search = {
    engine:  Components.classes["@mozilla.org/browser/nav-history-service;1"]
                       .getService(Components.interfaces.nsINavHistoryService),
    ios:     Components.classes["@mozilla.org/network/io-service;1"]
                       .getService(Components.interfaces.nsIIOService),
    history: Components.classes["@mozilla.org/browser/nav-history-service;1"]
                       .getService(Components.interfaces.nsIBrowserHistory)
};
search.options = search.engine.getNewQueryOptions();
search.options.sortingMode = Components.interfaces.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING;
search.options.maxResults = 300;
//search.options.resultType = Components.interfaces.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY;
search.query = search.engine.getNewQuery();
search.query.searchTerms = inputparams.q;
search.query.beginTime = inputparams.a ? inputparams.a * 1000 : 0;
search.query.endTime = inputparams.b ? inputparams.b * 1000 : 0;
search.query.domainIsHost = false;
search.query.domain = inputparams.s ? inputparams.s : null;
search.results = search.engine.executeQuery(search.query, search.options).root;
search.results.containerOpen = true;
search.displayResults = function(start) {
    var copyrowNew, dt, uri, i, node;
    if (start === undefined) {
        start = inputparams.start + 1;
    }
    inputparams.start = start;
    //remove existing results, highlight the appropriate page marker
    $('table#results tr[id!=copyrow]').remove();
    $('ul li').removeClass('selected');
    $('ul li:nth-child(' + (inputparams.start + 1) + ')').addClass('selected');
    //hide the next page if we're at the last page already
    $('ul li:last').css("display", (start + 1) * search.options.maxResults / 10 > search.results.childCount ? "none" : "inline");
    
    for (i = start * search.options.maxResults / 10; i < search.results.childCount && i < (start + 1) * search.options.maxResults / 10; i++) {
        node = search.results.getChild(i);
        copyrowNew = $("#copyrow").clone().removeAttr("id");
        dt = new Date(node.time / 1000);
        uri = search.ios.newURI(node.uri, null, null);
        copyrowNew.find(":checked").removeAttr("checked");
        copyrowNew.find("td a.date").text($.datepicker.formatDate("dd M yy", dt));
        copyrowNew.find("td a.date").attr("href", "javascript:filterDate('" + $.datepicker.formatDate("dd M yy", dt) + "')");
        copyrowNew.find("td.image img").attr("src", node.icon && node.icon.spec);
        copyrowNew.find("td.url a.page").attr("href", node.uri);
        copyrowNew.find("td.url a.page").text(node.title);
        copyrowNew.find("td.url a.site").attr("href", "javascript:filterSite('" + uri.host + "')");
        copyrowNew.find("td.url a.site").text(uri.host);
        copyrowNew.find("td.url span.time").text((dt.getHours() < 10 ? '0' : '')  + dt.getHours() + ":" + 
                                                 (dt.getMinutes() < 10 ? '0' : '')  + dt.getMinutes());
        $('table#results').append(copyrowNew);
    }
};
var ui = {
    toggleSearch: function(state) {
        if (state === 'simple') {
            //set to simple status.
            $('#qSimple').val($('#qAdvanced').val());
            $('#aAdvanced').val('');
            $('#bAdvanced').val('');
            $('#qAdvanced').val('');
        } else {
            //set to advanced status.
            $('#qAdvanced').val($('#qSimple').val());
            $('#qSimple').val('');
        }
        $('#state').val(state);
        $('form div').toggleClass("display");
    },
    filterDate: function(d) {
        if ($('#state').val() !== 'advanced') {
            ui.toggleSearch('advanced');
        }
        var dt = isNaN((new Date(d)).getFullYear()) ? "" : (new Date(d));
        var dtOneDayLater = new Date();
        if (dt) {
            dtOneDayLater.setTime(dt.getTime() + 24 * 60 * 60 * 1000);
            $('#aAdvanced').val($.datepicker.formatDate("dd M yy", dt));
            $('#bAdvanced').val($.datepicker.formatDate("dd M yy", dtOneDayLater));
        }
        $('form').submit();
    },
    filterSite: function(s) {
        if ($('#state').val() !== 'advanced') {
            ui.toggleSearch('advanced');
        }
        $('#sAdvanced').val(s);
        $('form').submit();
    },
    selectAllNone: function(s) {
        $('table input:checkbox').attr("checked", s);
    },
    deleteHistory: function() {
        $('table input:checked').parents("tr").find("a.page").each(function() {
            search.history.removePage(search.ios.newURI(this.href, null, null));
        });
        $('form').submit();
    }
};
$(document).ready(function(){
    //prepare UI: fill out search input element, datepicker
    $('#state').val(inputparams.state ? inputparams.state : "simple");
    $('#aAdvanced').datepicker({ dateFormat: 'dd M yy'});
    $('#aAdvanced').val(inputparams.a === "" ? "" : $.datepicker.formatDate("dd M yy", inputparams.a));
    $('#bAdvanced').datepicker({ dateFormat: 'dd M yy'});
    $('#bAdvanced').val(inputparams.b === "" ? "" : $.datepicker.formatDate("dd M yy", inputparams.b));
    $('#qAdvanced').val(inputparams.q);
    $('#sAdvanced').val(inputparams.s);
    $('#qSimple').val(inputparams.q);
    $('#start').val(inputparams.start);
    if ($('#state').val() === 'advanced') {
        $('form div').toggleClass("display");
    }
    //remove links to other results pages if there are no more results
    if (search.results.childCount < search.options.maxResults) {
        $('ul#nextresults li').slice(Math.floor(search.results.childCount * 10 / search.options.maxResults) + 1, 10).remove();
    }
    $('form').submit(function() {
        if ($('#state').val() === 'simple') {
            $('#a').val("");
            $('#b').val("");
            $('#q').val($('#qSimple').val());
        } else {
            $('#a').val($('#aAdvanced').val());
            $('#b').val($('#bAdvanced').val());
            $('#q').val($('#qAdvanced').val());
            $('#s').val($('#sAdvanced').val());
        }
    });
    search.displayResults(inputparams.start);
});

